import 'dart:io';
import 'package:lcapp/api/request/api_client.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:path_provider/path_provider.dart';

class FileTool{
  //获取本地存取路径的目录
  static Future<String> getStorageDir({String? relativePath}) async{
    Directory fileDr = await getTemporaryDirectory();
    String dirPath = fileDr.path+'/';
    dirPath += relativePath!=null?relativePath:"";
    await Directory(dirPath).create(recursive: true);
    return dirPath;
  }
  static Future<bool> isFileExist(path) async {
    String dirPath = await getStorageDir();
    File file = File(dirPath+path);
    bool isExist = await file.exists();

    return isExist;
  }
  static Future<Map> downloadFile(String networkUrl,String fileName, {String? extraDirPath}) async{
    String dirPath = await getStorageDir();
    if(extraDirPath!=null){
      dirPath = dirPath+ extraDirPath;
    }
    await Directory(dirPath).create(recursive: true);
    ResponseData downloadData = await ApiClient.download(
        networkUrl,
        dirPath+fileName);
    if (downloadData.success) {
      return {'state':'succ','path':dirPath+fileName};
      //print(downloadData);
    } else {
      return {'state':'fail','path':dirPath+fileName};
      //print("处理接口调用错误后的逻辑");
    }

  }

  static String getFileName(String path) {
    var index1 = path.lastIndexOf("/");
    var index2 = path.length;
    var fileName = path.substring(index1 + 1, index2);
    return fileName;
  }

  // 截取文件后缀
  static String getSuffixName(String path) {
    var index1 = path.lastIndexOf(".");
    var index2 = path.length;
    var type = path.substring(index1,index2).toUpperCase();
    return type;
  }

}